const { Op } = require("sequelize");
const models = require("../../model");
const { APIError } = require("../../rest");

const Products = models.Product;
const Categorys = models.ProductCategory;

// 定义商品模型
class ProductModel {
  // 创建产品
  static async create(params) {
    let { title, manufacturer, price, category_id } = params;
    price = parseFloat(price);
    const hasProduct = await Products.findOne({
      where: {
        title,
      },
    });
    // 判断产品是否已存在
    if (hasProduct) {
      throw new APIError("product: existing", "产品已存在");
      // return false;
    }
    Products.create({
      title,
      manufacturer,
      price,
      category_id,
    });
  }

  // 查询列表
  static async queryList(query) {
    let { category_id, keyword, page, pageSize } = query;
    let filter = {};
    if (category_id) Object.assign(filter, { category_id });
    if (keyword) {
      Object.assign(filter, { title: { [Op.like]: `%${keyword}%` } });
    }

    page = +page;
    pageSize = +pageSize;
    const products = await Products.findAndCountAll({
      limit: pageSize, //每页10条
      offset: (page - 1) * pageSize,
      where: filter,
      order: [["createdTime", "DESC"]],
      include: [
        {
          model: Categorys,
          as: "category",
        },
      ],
    });

    return products;
  }

  // 删除商品
  static async delete(id) {
    const product = await Products.findOne({
      where: {
        id,
      },
    });

    if (!product) {
      throw new APIError("product: not_found", "产品不存在！");
    }
    // 软删除产品
    product.destroy();
  }

  // 更新商品
  static async update(params) {
    let { id, title, manufacturer, price, category_id } = params;
    price = parseFloat(price);
    // 查询当前商品
    let product = await Products.findByPk(id);
    if (!product) {
      throw new APIError("product: not_found", "产品不存在！");
    }
    product.title = title;
    product.manufacturer = manufacturer;
    product.price = price;
    product.category_id = category_id;
    product.save();
  }

  static async detail(id) {
    const product = await Products.findOne({
      where: {
        id,
      },
    });
    if (!product) {
      throw new APIError("product: not_found", "产品不存在！");
    }

    return product;
  }
}

module.exports = {
  Products: ProductModel,
};
